const { School, Region, SchoolClass } = require('../models');
const { Op } = require('sequelize');
const dayjs = require('dayjs');

class SchoolService {
	static injector(ctn) {
		return [
			ctn.make('varal.app')
		]
	}
	constructor(app) {
		this.app = app;
	}

	async get(filter, page = 1, page_size = 20) {
		const { name, province_id, city_id } = filter;
		const where = {};
		if (name) where['name'] = { [Op.like]: `%${name}%` };
		if (province_id) where['province_id'] = province_id;
		if (city_id) where['city_id'] = city_id;

		const { count: total, rows: data } = await School.findAndCountAll({
			where,
			include: [{
				model: Region,
				as: 'province',
				attributes: ['name', 'id']
			}, {
				model: Region,
				as: 'city',
				attributes: ['name', 'id']
			}, {
				model: SchoolClass,
				as: 'classes'
			}],

			offset: (page - 1) * page_size,
			limit: page_size * 1,
			order: [
				['id', 'asc'],
				['classes', 'id', 'asc']
			]
		});

		return {
			data,
			total
		}
	}

	async info(where) {
		return await School.findOne({
			where
		});
	}

	async delete(id) {
		const schools = await School.findAll({
			where: {
				id: { [Op.in]: String(id).split(',') }
			},
			include: 'classes'
		});

		for (const school of schools) {
			await school.removeClasses(school.classes);

			//await school.setClasses([]);

			await school.destroy();
		}

		return true;
	}

	async save(params) {
		['create_time', 'update_time', 'delete_time'].forEach((d) => {
			delete params[d];
		});

		const { id } = params;
		params.price = parseFloat(params.price);

		if (!params.province_id) delete params.province_id;
		if (!params.city_id) delete params.city_id;
		params.classes = JSON.parse(params.classes || '[]');

		let school;

		if (id) {
			await School.update(params, {
				where: {
					id
				}
			})
			school = await School.findOne({
				where: {
					id
				},
				include: 'classes'
			});

			//方法1
			const classes = await Promise.all(params.classes.map((clazz) => SchoolClass.findOrCreate({
				where: { id: clazz?.id || null },
				defaults: clazz
			}).then(([instance]) => instance.update(clazz, {
				where: { id: instance.id }
			}))));

			//await school.addClasses(classes);
			//await Promise.all(classes.map((clazz) => school.addClass(clazz)));

			await school.setClasses(classes);

			//方法2
			//先删除再创建
			/*
			await SchoolClass.destroy({
				where: { school_id: id },
				force: true
			});
			await Promise.all(params.classes.map((clazz) => school.createClass(clazz)));
			*/
		} else {
			school = await School.create(params, {
				include: [{
					association: School.Classes,
					as: 'classes'
				}]
			});
		}

		return school;
	}
}

exports = module.exports = SchoolService;
